import React, { useState, useRef } from "react";
import Canvas, { CanvasRef } from "./Canvas";
import ControlPanel from "./ControlPanel";
import ProductList from "./ProductList";
import { Pattern, PatternInstance } from "../../types/editor";
import pattern1 from "../../assest/image/bm.png";
import pattern2 from "../../assest/image/bom.png";
import { 
  Page, 
  Layout, 
  Card, 
  Button,
  Frame,
  Toast,
  Tabs
} from '@shopify/polaris';

// 示例图案数据
const samplePatterns: Pattern[] = [
  {
    id: "pattern1",
    name: "图案1",
    imageUrl: pattern1,
    thumbnailUrl: pattern1,
  },
  {
    id: "pattern2",
    name: "图案2",
    imageUrl: pattern2,
    thumbnailUrl: pattern2,
  },
];

const TshirtEditor: React.FC = () => {
  const [patterns, setPatterns] = useState<PatternInstance[]>([]);
  const [selectedPatternId, setSelectedPatternId] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [toastActive, setToastActive] = useState(false);
  const [toastContent, setToastContent] = useState({ content: '', error: false });
  const [selectedTab, setSelectedTab] = useState(0);
  const [selectedProduct, setSelectedProduct] = useState<any>(null);
  const [isEditingProduct, setIsEditingProduct] = useState(false);
  const canvasRef = useRef<CanvasRef>(null);

  // 标签页定义
  const tabs = [
    {
      id: 'patterns',
      content: '图案编辑',
    },
    {
      id: 'products',
      content: '商品列表',
    },
  ];

  // 处理选择商品
  const handleSelectProduct = async (product: any) => {
    console.log('选中商品:', product);
    setSelectedProduct(product);
    
    try {
      // 先清空现有图案
      setPatterns([]);
      
      if (product.images && product.images.length > 0) {
        // 把商品的第一张图片加载到编辑器
        const imageUrl = product.images[0].src;
        // 创建一个新的图案实例
        const newPattern: PatternInstance = {
          id: `product-image-${product.id}`,
          patternId: imageUrl, // 这里直接使用图片URL
          x: 200, // 居中位置
          y: 250,
          scaleX: 0.5,
          scaleY: 0.5,
          angle: 0,
          productImageId: product.images[0].id // 存储Shopify图片ID，用于更新
        };
        
        setPatterns([newPattern]);
        setIsEditingProduct(true);
      } else {
        setToastContent({
          content: "该商品没有图片",
          error: true
        });
        setToastActive(true);
      }
    } catch (error) {
      console.error('加载商品图片失败:', error);
      setToastContent({
        content: "加载商品图片失败",
        error: true
      });
      setToastActive(true);
    }
  };

  const handleAddPattern = (patternId: string) => {
    console.log("Adding pattern:", patternId);
    const pattern = samplePatterns.find((p) => p.id === patternId);
    if (pattern) {
      console.log("Found pattern:", pattern);
      const newPattern: PatternInstance = {
        id: `${patternId}-${Date.now()}`,
        patternId: pattern.imageUrl,
        x: 200, // 居中位置
        y: 250,
        scaleX: 1,
        scaleY: 1,
        angle: 0,
      };
      console.log("Created new pattern instance:", newPattern);
      setPatterns([...patterns, newPattern]);
    } else {
      console.error("Pattern not found:", patternId);
    }
  };

  const handleUpdatePattern = (updatedPattern: PatternInstance) => {
    setPatterns(
      patterns.map((p) => (p.id === updatedPattern.id ? updatedPattern : p))
    );
  };

  const handleDeletePattern = (id: string) => {
    setPatterns(patterns.filter((p) => p.id !== id));
    if (selectedPatternId === id) {
      setSelectedPatternId(null);
    }
  };

  // 保存新设计
  const handleSaveNewDesign = async () => {
    if (!canvasRef.current) {
      setToastContent({
        content: "无法获取设计数据，请稍后再试",
        error: true
      });
      setToastActive(true);
      return;
    }

    try {
      setIsSaving(true);
      const designData = canvasRef.current.getCanvasData();
      console.log("保存设计:", designData);
      
      setToastContent({
        content: "设计已保存",
        error: false
      });
      setToastActive(true);
    } catch (error: any) {
      console.error("保存设计失败:", error);
      setToastContent({
        content: `保存失败: ${error.message}`,
        error: true
      });
      setToastActive(true);
    } finally {
      setIsSaving(false);
    }
  };

  // 更新商品图片
  const handleUpdateProductImage = async () => {
    if (!canvasRef.current || !selectedProduct) {
      setToastContent({
        content: "无法获取设计数据或未选择商品",
        error: true
      });
      setToastActive(true);
      return;
    }

    try {
      setIsSaving(true);
      const designData = canvasRef.current.getCanvasData();
      console.log("更新商品图片:", designData);
      
      setToastContent({
        content: "商品图片已更新",
        error: false
      });
      setToastActive(true);
    } catch (error: any) {
      console.error("更新商品图片失败:", error);
      setToastContent({
        content: `更新失败: ${error.message}`,
        error: true
      });
      setToastActive(true);
    } finally {
      setIsSaving(false);
    }
  };

  // 处理保存按钮点击
  const handleSaveClick = () => {
    if (isEditingProduct && selectedProduct) {
      handleUpdateProductImage();
    } else {
      handleSaveNewDesign();
    }
  };

  // 处理Toast关闭
  const dismissToast = () => setToastActive(false);

  const selectedPattern =
    patterns.find((p) => p.id === selectedPatternId) || null;

  const toastMarkup = toastActive ? (
    <Toast
      content={toastContent.content}
      error={toastContent.error}
      onDismiss={dismissToast}
    />
  ) : null;

  // 清除当前编辑状态，创建新设计
  const handleNewDesign = () => {
    setPatterns([]);
    setSelectedProduct(null);
    setIsEditingProduct(false);
  };

  // 获取 access_token
  const handleGetAccessToken = async () => {
    try {
      const response = await fetch('/api/auth/token');
      const data = await response.json();
      
      if (data.success) {
        setToastContent({
          content: `成功获取 Shopify API Token`,
          error: false
        });
        setToastActive(true);
        console.log('Shopify API Access Token:', data.access_token);
        console.log('Shop Domain:', data.shop);
      } else {
        throw new Error(data.error || '获取 Shopify API Token 失败');
      }
    } catch (error: any) {
      console.error('获取 Shopify API Token 失败:', error);
      setToastContent({
        content: `获取 Shopify API Token 失败: ${error.message}`,
        error: true
      });
      setToastActive(true);
    }
  };

  // 直接请求 /admin/oauth/access_token（仅测试用）
  const handleExchangeAccessToken = async () => {
    try {
      const shop = window.prompt('输入店铺域名（例如 my-shop.myshopify.com）');
      if (!shop) return;
      const code = window.prompt('输入授权 code');
      if (!code) return;
      const redirectUri = window.prompt('可选：输入 redirect_uri（与应用配置一致）') || undefined;

      const response = await fetch('/api/auth/exchange', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ shop, code, redirectUri })
      });
      const data = await response.json();

      if (data.success) {
        setToastContent({
          content: '交换成功，已获取 access_token（见控制台）',
          error: false
        });
        setToastActive(true);
        console.log('Exchange result:', data.data);
      } else {
        throw new Error(data.error || '交换失败');
      }
    } catch (error: any) {
      console.error('交换 access_token 失败:', error);
      setToastContent({
        content: `交换失败: ${error.message}`,
        error: true
      });
      setToastActive(true);
    }
  };

  // 发起 OAuth 并自动捕获 code
  const handleStartOAuth = async () => {
    try {
      const shop = window.prompt('输入店铺域名（例如 my-shop.myshopify.com）');
      if (!shop) return;
      const state = Math.random().toString(36).slice(2);
      const forward = window.prompt('可选：授权后转发到外部地址（将携带 code/state/shop）');
      const method = forward ? (window.prompt('转发方法（get 或 post，默认 get）') || 'get') : '';

      // Open a blank popup synchronously to avoid popup blockers
      const popup = window.open('about:blank', 'shopify_oauth', 'width=480,height=720,noopener,noreferrer');
      const popupBlocked = !popup;
      if (!popupBlocked) {
        try {
          popup.document.write('<p style="font-family:sans-serif">正在加载授权页面…</p>');
        } catch {}
      }

      const search = new URLSearchParams({ shop, state });
      if (forward) search.set('forward', forward);
      if (method) search.set('method', method.toLowerCase());
      const urlResp = await fetch(`/api/auth/authorize-url?${search.toString()}`);
      const urlData = await urlResp.json();
      if (!urlData.success || !urlData.authorizeUrl) {
        try { if (popup) { popup.close(); } } catch {}
        throw new Error(urlData.error || '生成授权地址失败');
      }

      const authUrl = urlData.authorizeUrl as string;

      // If embedded (inside iframe), prefer top-level redirect fallback
      const isEmbedded = window.top && window.top !== window.self;
      if (isEmbedded) {
        try { if (popup) { popup.close(); } } catch {}
        // Use top-level redirect to avoid third-party cookie/popup issues
        (window.top as Window).location.href = authUrl;
      } else if (popupBlocked) {
        // Fallback to current window if popup was blocked
        window.location.href = authUrl;
      } else {
        // Navigate the already-open popup
        if (popup) { popup.location.href = authUrl; }
      }

      const onMessage = async (event: MessageEvent) => {
        const data: any = event.data;
        if (!data || data.type !== 'shopify_oauth_code') return;
        if (data.state !== state) return;
        window.removeEventListener('message', onMessage);

        try {
          const response = await fetch('/api/auth/exchange', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ shop: data.shop || shop, code: data.code, redirectUri: urlData.redirectUri })
          });
          const resData = await response.json();

          if (resData.success) {
            setToastContent({ content: '授权完成，已获取 access_token（见控制台）', error: false });
            setToastActive(true);
            console.log('Exchange result:', resData.data);
          } else {
            throw new Error(resData.error || '交换失败');
          }
        } catch (err: any) {
          console.error('交换失败:', err);
          setToastContent({ content: `交换失败: ${err.message}`, error: true });
          setToastActive(true);
        }
      };

      window.addEventListener('message', onMessage);
    } catch (error: any) {
      console.error('启动授权失败:', error);
      setToastContent({ content: `启动授权失败: ${error.message}`, error: true });
      setToastActive(true);
    }
  };

  return (
    <Frame>
      <Page 
        title="T恤定制设计器" 
        titleMetadata={
          <div className="flex items-center space-x-3">
            {selectedProduct && (
              <span className="inline-flex items-center px-3 py-1 text-sm font-medium rounded-full bg-blue-100 text-blue-800">
                编辑中: {selectedProduct.title}
              </span>
            )}
            <Button onClick={handleGetAccessToken}>
              获取 Access Token
            </Button>
            <Button onClick={handleExchangeAccessToken}>
              交换 Admin Token（测试）
            </Button>
            <Button onClick={handleStartOAuth}>
              一键获取授权 code（测试）
            </Button>
          </div>
        }
      >
        {toastMarkup}
        <Layout>
          <Layout.Section variant="oneThird">
            <Card>
              <div className="p-4">
                <Tabs
                  tabs={tabs}
                  selected={selectedTab}
                  onSelect={(index) => setSelectedTab(index)}
                />
                
                <div className="mt-5">
                  {selectedTab === 0 ? (
                    <ControlPanel
                      availablePatterns={samplePatterns}
                      selectedPattern={selectedPattern}
                      onAddPattern={handleAddPattern}
                      onUpdatePattern={handleUpdatePattern}
                      onDeletePattern={handleDeletePattern}
                    />
                  ) : (
                    <ProductList 
                      onSelectProduct={handleSelectProduct}
                    />
                  )}
                </div>
              </div>
            </Card>
          </Layout.Section>
          
          <Layout.Section>
            <Card>
              <div className="p-4">
                <Canvas
                  ref={canvasRef}
                  patterns={patterns}
                  selectedPatternId={selectedPatternId}
                  onPatternSelect={setSelectedPatternId}
                  onPatternUpdate={handleUpdatePattern}
                />
              </div>
            </Card>

            <Card>
              <div className="p-5">
                <div className="space-y-5">
                  <div className="flex justify-between items-center pt-3">
                    <Button 
                      onClick={handleNewDesign}
                      disabled={isSaving}
                    >
                      {isEditingProduct ? '取消编辑商品' : '新建设计'}
                    </Button>
                    
                    <Button
                      onClick={handleSaveClick}
                      loading={isSaving}
                      disabled={patterns.length === 0}
                      variant="primary"
                    >
                      {isEditingProduct ? '更新商品图片' : '保存设计'}
                    </Button>
                  </div>

                  {selectedProduct && (
                    <div className="mt-5 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                      <div className="flex items-center space-x-3">
                        {selectedProduct.images && selectedProduct.images.length > 0 && (
                          <div className="w-12 h-12 flex-shrink-0 border rounded overflow-hidden">
                            <img 
                              src={selectedProduct.images[0].src} 
                              alt={selectedProduct.title}
                              className="w-full h-full object-cover"
                            />
                          </div>
                        )}
                        <div>
                          <h4 className="text-blue-800 font-medium">{selectedProduct.title}</h4>
                          <p className="text-sm text-blue-600">
                            商品ID: {selectedProduct.id.split('/').pop()}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          </Layout.Section>
        </Layout>
      </Page>
    </Frame>
  );
};

export default TshirtEditor;
